package org.helgoboss.janana_tray_repository_management

import scala.swing._
import scala.swing.event._
import org.osgi.service.obr.Repository
import javax.swing.UIManager
import org.helgoboss.scala_swing_additions.{MigPanel, ProgressView}
import javax.swing.table.TableModel
import javax.swing.event.TableModelListener
import java.awt.Toolkit
import org.helgoboss.janana_artwork.JananaLogo

abstract class RepositoryManagementView {

    private lazy val repositoryTable: Table = new Table {
        focusable = true
        
        listenTo(keys)
        
        reactions += {
            case KeyPressed(_, Key.Delete, _, _) =>
                removeSelectedRepository
        }
        
        model = new TableModel {        
            def addTableModelListener(listener: TableModelListener) {
            }
            
            def removeTableModelListener(listener: TableModelListener) {
            }
            
            def getColumnClass(columnIndex: Int) = classOf[String]
            
            def getColumnCount = 2
            
            def getColumnName(columnIndex: Int) = columnIndex match {
                case 0 => "URL"
                case 1 => "Name"
            }
            
            def getRowCount = repositories.size
            
            def getValueAt(rowIndex: Int, columnIndex: Int) = {
                val repository = repositories(rowIndex)
                columnIndex match {
                    case 0 => repository.getURL.toString
                    case 1 => repository.getName
                }
            }
            
            def isCellEditable(rowIndex: Int, columnIndex: Int) = false
            
            def setValueAt(value: AnyRef, rowIndex: Int, columnIndex: Int) {
            }
        }
    }
    
    
    private lazy val repositoryTextField: TextField = new TextField(50) {
        listenTo(keys)
        reactions += {
            case KeyPressed(_, Key.Enter, _, _) =>
                addEnteredRepository
        }
    }
    
    private lazy val progressView: ProgressView = new ProgressView(host = Some(frame), dialogTitle = "Janana")
    
    private var repositories: Seq[Repository] = Nil
    

    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName)
    
    private lazy val frame = new Frame {
        title = "Janana Repository Management"
        iconImage = JananaLogo.medium
        preferredSize = new Dimension(800, 500)
        val screenSize = Toolkit.getDefaultToolkit.getScreenSize 
        
        location = new Point(
            (screenSize.getWidth / 2 - preferredSize.getWidth / 2).asInstanceOf[Int], 
            (screenSize.getHeight / 2 - preferredSize.getHeight / 2).asInstanceOf[Int]
        )
        
        
        contents = new MigPanel("wrap 1", "[grow,fill]", "[grow,fill][fill]") {
            this add new ScrollPane {
                viewportView = repositoryTable
            }
            this add new FlowPanel {
                contents += repositoryTextField
                contents += Button("Add") { 
                    addEnteredRepository
                }
                val chooseLocalButton: Button = Button("Choose local ...") {
                    val chooser = new FileChooser
                    chooser.showOpenDialog(chooseLocalButton)
                    if (chooser.selectedFile != null)
                        repositoryTextField.text = chooser.selectedFile.toURI.toString
                }
                contents += chooseLocalButton
            }
        }
        override def closeOperation { 
            hide
        }
    }
   
    private def addEnteredRepository {
        progressView.showForOperation("Adding repository") {
            addRepository(repositoryTextField.text)
        }
        repositoryTextField.text = ""
        updateRepositoryTable
    }
    
    
    private def removeSelectedRepository {
        selectedRepository.foreach(removeRepository)
        updateRepositoryTable
    }
    
    private def selectedRepository = {
        val selectedIndices = repositoryTable.selection.rows
        if (selectedIndices.size > 0) {
            Some(repositories(selectedIndices.head))
        } else {
            None
        }
    }
    
    def updateRepositoryAddingProgress(progress: Int) {
        progressView.updateProgress(progress)
    }
           
    def addRepository(repositoryUrlString: String)
    
    def removeRepository(repository: Repository)
    
    def obtainRepositories: Seq[Repository]
    
    private def updateRepositoryTable {
        repositories = obtainRepositories
        repositoryTable.revalidate
    }
    
    def show {
        Swing.onEDT {
            /* Load frame */
            frame
            
            updateRepositoryTable
            frame.visible = true
        }
    }
    
    def hide {
        Swing.onEDT {
            frame.visible = false
        }
    }
    
    def dispose {
        Swing.onEDT {
            frame.dispose
        }
    }

}
